/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2013 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Combination image + drop-down field
 * @author tmickel@mit.edu (Tim Mickel)
 */
'use strict';
goog.provide('Blockly.FieldImageDropdown');

goog.require('Blockly.DropDownDiv');
goog.require('Blockly.FieldDropdown');
goog.require('goog.userAgent');


/**
 * Class for a combination number + drop-down field.
 * @param {number|string} value The initial content of the field.
 * @param {(!Array.<!Array.<string>>|!Function)} menuGenerator An array of
 *     options for a dropdown list, or a function which generates these options.
 * @param {number|string|undefined} opt_min Minimum value.
 * @param {number|string|undefined} opt_max Maximum value.
 * @param {number|string|undefined} opt_precision Precision for value.
 * @param {Function=} opt_validator An optional function that is called
 *     to validate any constraints on what the user entered.  Takes the new
 *     text as an argument and returns the accepted text or null to abort
 *     the change.
 * @extends {Blockly.FieldDropdown}
 * @constructor
 */

/**
 * @class
 * @extends {Blockly.FieldDropdown}
 * @param {string} value 当前图像的 URL。
 * @param {!Array<!Array<string>>} options 下拉菜单选项数组。
 * @param {string} alt 图像的替代文本。
 * @param {number} width 图像的宽度。
 * @param {number} height 图像的高度。
 * @constructor
 */
Blockly.FieldImageDropdown = function( options) {
  // 调用父类构造函数
  console.log("000")
  // var firstTuple = this.getOptions()[0]
  Blockly.FieldImageDropdown.superClass_.constructor.call(this, options);

};

// 继承自 Blockly.FieldDropdown
goog.inherits(Blockly.FieldImageDropdown, Blockly.FieldDropdown);

/**
 * 初始化字段
 */

Blockly.FieldImageDropdown.prototype.dropdownCreate_ = function() {
  var container = document.createElement('div');
  container.className = 'blocklyDropdownImageMenu';

  this.getOptions().forEach(function(option) {
    console.log(option,"option")
    var item = document.createElement('div');
    item.className = 'blocklyDropdownImageItem';

    var img = document.createElement('img');
    img.src = option[0];  // Image URL
    img.alt = option[1];  // Option value

    var text = document.createElement('span');
    text.textContent = option[1];  // Option text

    item.appendChild(img);
    item.appendChild(text);
    container.appendChild(item);
  });
 console.log(container,"containercontainercontainercontainer")
  return container;
};
Blockly.FieldImageDropdown.prototype.init = function() {
  // if (this.fieldGroup_) {
  //   return; // 已经初始化过了
  // }

  Blockly.FieldImageDropdown.superClass_.init.call(this);
  var options = this.getOptions();
  var contentDiv = Blockly.DropDownDiv.getContentDiv();

  var thisField = this;

  function callback(e) {
    var menu = this;
    var menuItem = e.target;
    if (menuItem) {
      thisField.onItemSelected(menu, menuItem);
    }
    Blockly.DropDownDiv.hide();
    Blockly.Events.setGroup(false);
  }
  // 创建图像元素
  // var buttonContainer = document.createElement('div');
  var buttonContainer = new goog.ui.Menu();
  // this.image_ = new Image();
  // this.image_.src = options[0][1];
  // this.image_.alt = "ese";
  // this.image_.width =  30;
  // this.image_.height = 30;
  // this.image_.style.cursor = 'pointer';

  // this.image_1 = new Image();
  // this.image_1.src = options[1][1];
  // this.image_1.alt = "ese";
  // this.image_1.width =  30;
  // this.image_1.height = 30;
  // this.image_1.style.cursor = 'pointer';

//   console.log(this.image,"444")
//   var child = this.fieldGroup_.getElementsByTagName("text")[0];
//  this.fieldGroup_.removeChild(child);
//   // 将图像添加到字段的 DOM 中
  // this.fieldGroup_.insertBefore(this.image_,this.fieldGroup_.children[0]);
// console.log(this.fieldGroup_,"fieldGroup_")
 
// this.imageElement_ = Blockly.utils.createSvgElement(
//   'image',
//   {
//     'height': 30 + 'px',
//     'width': 30 + 'px'
//   },null);
//   this.imageElement_.setAttributeNS('http://www.w3.org/1999/xlink',
//     'xlink:href', options[0][1] || '');
// this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_);
// var menuItem = new goog.ui.MenuItem(this.imageElement_);
// var menuItem1 = new goog.ui.ImageMenuItem(options[0][1]);

// console.log(menuItem1,"menuItem")
// buttonContainer.addItem(menuItem1,true);
// buttonContainer.addChild(this.image_1,true);

// goog.events.listen(buttonContainer, goog.ui.Component.EventType.ACTION, callback);

// buttonContainer.render(contentDiv);

// 绑定点击事件
 
 
// this.imageElement_.addEventListener('click', this.showMenu.bind(this));
 
};

// 创建一个自定义的菜单项类，支持图片
goog.ui.ImageMenuItem = function(content, opt_className, opt_domHelper) {
  goog.ui.ImageMenuItem.base(this, 'constructor', content, opt_className, opt_domHelper);
};
goog.inherits(goog.ui.ImageMenuItem, goog.ui.MenuItem);

// 重写 `createDom` 方法，以插入图片
goog.ui.ImageMenuItem.prototype.createDom = function() {
  var dom = this.getDomHelper();
  var element = dom.createDom('div');

  // 创建图片元素
  var img = dom.createDom('img', {
    'src': this.content_,
    'alt': '',
    'style': 'width: 30px; height: 30px;'
  });

  // 将图片元素添加到菜单项中
  dom.appendChild(element, img);

  // 设置菜单项的 DOM 元素
  this.setElementInternal(element);
};

/**
 * 更新下拉菜单的内容
 */
Blockly.FieldImageDropdown.prototype.updateMenu = function() {
  // 使用父类方法获取菜单项
  var options = this.options_;

  this.menu_ = document.createElement('div');
  this.menu_.className = 'blocklyFieldImageDropdownMenu';
  this.menu_.style.position = 'absolute';
  this.menu_.style.display = 'none';

  for (var i=0;i< options.length;i++) {
    var img = document.createElement('img');
    img.src = option[1];
    img.alt = option[0];
    img.style.cursor = 'pointer';
    img.style.width = '50px'; // 设置菜单图像的宽度
    img.style.height = '50px'; // 设置菜单图像的高度
    img.addEventListener('click', () => this.setValue(option[1]));
    this.menu_.appendChild(img);
  }

  document.body.appendChild(this.menu_);
  console.log(options,"options")
};

/**
 * 显示下拉菜单
 */
Blockly.FieldImageDropdown.prototype.showMenu = function() {
  if (!this.menu_) {
    this.updateMenu();
  }

  // 创建下拉菜单的 DOM 元素
  var menu = document.createElement('ul');
  menu.style.position = 'absolute';
  menu.style.zIndex = '1000';
  menu.style.border = '1px solid #ccc';
  menu.style.backgroundColor = '#fff';
  menu.style.listStyleType = 'none';
  menu.style.padding = '0';
  menu.style.margin = '0';
  this.menu_ = menu;

  var options = this.options_;
  var self = this;

  options.forEach(function(option) {
    var item = document.createElement('li');
    item.textContent = option[0];
    item.dataset.value = option[1];
    item.style.padding = '5px';
    item.style.cursor = 'pointer';
    item.addEventListener('click', function() {
      self.setValue(item.dataset.value);
      self.hideMenu();
    });
    menu.appendChild(item);
  });

  // 显示菜单
  document.body.appendChild(menu);

  // 计算和设置菜单位置
  var rect = this.image_.getBoundingClientRect();
  menu.style.top = (rect.bottom + window.scrollY) + 'px';
  menu.style.left = (rect.left + window.scrollX) + 'px';


   // 点击菜单外部隐藏菜单
   function onClickOutside(event) {
    if (!menu.contains(event.target) && event.target !== self.image_) {
      self.hideMenu();
      document.removeEventListener('click', onClickOutside);
    }
  }
  document.addEventListener('click', onClickOutside);
};

  // const rect = this.image_.getBoundingClientRect();
  // this.menu_.style.top = (rect.bottom + window.scrollY) + 'px';
  // this.menu_.style.left = (rect.left + window.scrollX) + 'px';
  // this.menu_.style.display = 'block';
  
  // // 隐藏菜单的点击事件
  // document.addEventListener('click', this.hideMenu.bind(this));
  // console.log(2222)
// };

/**
 * 隐藏下拉菜单
 */
// Blockly.FieldImageDropdown.prototype.hideMenu = function(event) {
//   if (!this.menu_.contains(event.target) && event.target !== this.image_) {
//     this.menu_.style.display = 'none';
//     document.removeEventListener('click', this.hideMenu.bind(this));
//   }
// };

/**
 * 隐藏下拉菜单
 */
Blockly.FieldImageDropdown.prototype.hideMenu = function() {
  if (this.menu_) {
    document.body.removeChild(this.menu_);
    this.menu_ = null;
  }
};

/**
 * 设置字段的值并更新显示的图片
 * @param {string} value
 */
Blockly.FieldImageDropdown.prototype.setValue = function(value) {
  this.value_ = value;
  if (this.image_) {
    this.image_.src = value;
  }
  this.updateEditable();
};

/**
 * 从 JSON 对象中恢复 FieldImageDropdown。
 * @param {!Object} json JSON 对象。
 * @return {!Blockly.FieldImageDropdown} 新的 FieldImageDropdown 实例。
 * @package
 */
Blockly.FieldImageDropdown.fromJson = function(json) {
  console.log(333,json['options'])

  return new Blockly.FieldImageDropdown(
    json['options'], 
  );
};

// Blockly.FieldImageDropdown.prototype.getOptionsDropdown = function() {
//   var options = this.getOptions();
//   var content = document.createElement('div');
//   for (var i = 0; i < options.length; i++) {
//     var option = options[i];
//     var img = document.createElement('image');
//     img.setAttributeNS('http://www.w3.org/1999/xlink',
//         'xlink:href', option[0] || '');
//     // .setAttribute('src', option[0]);
//     img.style.width = '16px';
//     img.style.height = '16px';
//     img.style.cursor = 'pointer';
//     img.addEventListener('click', (function(value) {
//       return function() {
//         this.setValue(value);
//         Blockly.DropDownDiv.hideWithoutAnimation();
//       }.bind(this);
//     }).bind(this, option[1]));
   
//     content.appendChild(img);
//   }
 
//   return content;
// };
Blockly.Field.register('field_image_dropdown', Blockly.FieldImageDropdown);
